//
//  TTADView.m
//  TaoTuo
//
//  Created by admin on 2019/10/23.
//  Copyright © 2019 admin. All rights reserved.
//

#import "TTADView.h"
#import "TTHomeBanner.h"
#import <UIImageView+WebCache.h>

@interface TTADView ()

@property (nonatomic, strong) UIImageView *imageView;
@property (nonatomic, strong) UILabel *timeLabel;   // 倒计时
@property (nonatomic, strong) UIButton *skipBtn;    // 跳过
@property (nonatomic, strong) TTHomeBanner *bannerModel;

@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) NSInteger count;

@property (nonatomic, copy) dispatch_block_t dismissBlock;

@end

@implementation TTADView

+ (instancetype)adViewAndDismissBlock:(dispatch_block_t)dismissBlock
{
    return [[self alloc] initWithFrame:[UIScreen mainScreen].bounds dismissBlock:dismissBlock];
}

- (instancetype)initWithFrame:(CGRect)frame dismissBlock:(dispatch_block_t)dismissBlock
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        
        self.dismissBlock = dismissBlock;
        
        [self setupSubviews];
        
        [self getAdDatas];
        
        [[UIApplication sharedApplication].keyWindow addSubview:self];
        
        NSDictionary *dic = [USER_DEFAULT objectForKey:ad_data_key];
        NSData *imageData = [USER_DEFAULT objectForKey:@"ad_image_data_key"];
        if (dic && imageData) {
            UIImage *image = [UIImage imageWithData:imageData];
            [self handleAdDataWithDic:dic image:image];
        } else {
            [self removeFromSuperview];
            if (self.dismissBlock) {
                self.dismissBlock();
            }
        }
        
    }
    return self;
}

// 跳过
- (void)clickSkipTap
{
    [self dismiss];
}

// 点击图片了
- (void)clickImageView
{
    [self dismiss];
    
    [LLRouteTool skipViewControllerWIthSkipType:self.bannerModel.SkipType skipTarget:self.bannerModel.SkipTarget];
}


- (void)handleAdDataWithDic:(NSDictionary *)dic image:(UIImage *)image
{
    self.bannerModel = [TTHomeBanner modelWithJSON:dic];
    
    self.imageView.image = image;
    
    self.timeLabel.text = self.bannerModel.Time;
    
    self.count = self.bannerModel.Time.integerValue;
    
    if (self.timer == nil) {
        YYWeakProxy *proxy = [YYWeakProxy proxyWithTarget:self];
        self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:proxy selector:@selector(timerAction) userInfo:nil repeats:YES];
    }
    
}


- (void)timerAction
{
    self.count--;
    if (self.count == 0) {
        [self dismiss];
        return;
    }
    self.timeLabel.text = [NSString stringWithFormat:@"%ld", self.count];
}

- (void)getAdDatas
{
    @weakify(self)
    [[LLNetworkManagerTool sharedManager] requestMethod:GET urlString:ad_api parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self)
        NSDictionary *dic = responseObject;
        NSString *imageUrlString = dic[@"ImageUrl"];
        if (imageUrlString.length > 0) {
            NSURL *url = [NSURL URLWithString:imageUrlString];
            // 下载图片
            @weakify(self)
            [[SDWebImageManager sharedManager] loadImageWithURL:url options:SDWebImageRetryFailed progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
                
            } completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
                @strongify(self)
                if (error) return;
                
                [self handleAdDataWithDic:dic image:image];
                //TODO: 保存banner
                [USER_DEFAULT setObject:dic forKey:ad_data_key];
                NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
                [USER_DEFAULT setObject:imageData forKey:@"ad_image_data_key"];
            }];
            
            
        } else {
            [self dismiss];
        }
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        @strongify(self)
        [self dismiss];
        
    } showLoadingInView:nil];
}


- (void)dismiss
{
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
    
    [UIView animateWithDuration:0.5 animations:^{
        
        self.transform = CGAffineTransformMakeScale(1.5, 1.5);
        self.alpha = 0;
        
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
        
        if (self.dismissBlock) {
            self.dismissBlock();
        }
    }];
}


- (void)setupSubviews
{
    _imageView = [[UIImageView alloc] initWithFrame:self.bounds];
    _imageView.contentMode = UIViewContentModeScaleAspectFill;
    _imageView.userInteractionEnabled = YES;
    [self addSubview:_imageView];
    
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickImageView)];
    [_imageView addGestureRecognizer:tap];
    
    UIView *timeBGView = [[UIView alloc] init];
    timeBGView.layer.cornerRadius = 15;
    timeBGView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.4];
    [_imageView addSubview:timeBGView];
    [timeBGView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.imageView).mas_offset(-10);
        make.height.mas_equalTo(30);
        make.width.mas_equalTo(90);
        make.bottom.equalTo(self.imageView).mas_offset(-30);
    }];
    UITapGestureRecognizer *skipTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickSkipTap)];
    [timeBGView addGestureRecognizer:skipTap];
    
    _timeLabel = [UILabel labelTextCenterWithTitle:@"" color:[UIColor whiteColor] fontSize:18];
    [timeBGView addSubview:_timeLabel];
    [_timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.height.equalTo(timeBGView);
        make.width.mas_equalTo(30);
    }];
    
    [timeBGView layoutIfNeeded];
    
    _skipBtn = [UIButton createButtonWithFrame:CGRectMake(_timeLabel.right, 0, 60, timeBGView.height) image:[UIImage imageNamed:@"adskiparrow"] title:@"跳过" titleColor:[UIColor whiteColor] titleFont:[UIFont systemFontOfSize:15] space:3 backgroundColor:nil target:self action:@selector(clickSkipTap)];
    [timeBGView addSubview:_skipBtn];
    
}

- (void)dealloc
{
    NSLog(@"广告页面释放了");
}

@end
